#include "memostorage.h"
#include <QDateTime>
#include <algorithm>

MemoStorage::MemoStorage(QObject *parent)
    : QObject(parent)
{
    ensureStorageDir();
}

QString MemoStorage::getStoragePath()
{
    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir dir;
    if (!dir.exists(dataPath)) {
        dir.mkpath(dataPath);
    }
    return dataPath + "/memos.json";
}

void MemoStorage::ensureStorageDir()
{
    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir dir;
    if (!dir.exists(dataPath)) {
        dir.mkpath(dataPath);
    }
}

QJsonArray MemoStorage::loadJsonArray()
{
    QString filePath = getStoragePath();
    QFile file(filePath);
    
    if (!file.exists()) {
        return QJsonArray();
    }
    
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开文件:" << filePath;
        return QJsonArray();
    }
    
    QByteArray data = file.readAll();
    file.close();
    
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull() || !doc.isArray()) {
        return QJsonArray();
    }
    
    return doc.array();
}

bool MemoStorage::saveJsonArray(const QJsonArray &array)
{
    QString filePath = getStoragePath();
    QFile file(filePath);
    
    if (!file.open(QIODevice::WriteOnly)) {
        qWarning() << "无法写入文件:" << filePath;
        return false;
    }
    
    QJsonDocument doc(array);
    file.write(doc.toJson());
    file.close();
    
    return true;
}

QVariantList MemoStorage::loadMemos()
{
    QJsonArray array = loadJsonArray();
    QVariantList result;
    
    for (int i = 0; i < array.size(); i++) {
        QJsonObject obj = array[i].toObject();
        QVariantMap map;
        map["id"] = obj["id"].toInt();
        map["title"] = obj["title"].toString();
        map["content"] = obj["content"].toString();
        map["createdAt"] = obj["createdAt"].toString();
        map["updatedAt"] = obj["updatedAt"].toString();
        result.append(map);
    }
    
    // 按更新时间倒序排序
    std::sort(result.begin(), result.end(), [](const QVariant &a, const QVariant &b) {
        QVariantMap mapA = a.toMap();
        QVariantMap mapB = b.toMap();
        return mapA["updatedAt"].toString() > mapB["updatedAt"].toString();
    });
    
    return result;
}

bool MemoStorage::saveMemo(int id, const QString &title, const QString &content)
{
    if (title.trimmed().isEmpty()) {
        return false;
    }
    
    QJsonArray array = loadJsonArray();
    QDateTime now = QDateTime::currentDateTime();
    QString nowStr = now.toString(Qt::ISODate);
    
    bool found = false;
    for (int i = 0; i < array.size(); i++) {
        QJsonObject obj = array[i].toObject();
        if (obj["id"].toInt() == id) {
            obj["title"] = title;
            obj["content"] = content;
            obj["updatedAt"] = nowStr;
            array[i] = obj;
            found = true;
            break;
        }
    }
    
    if (!found) {
        // 新建
        QJsonObject obj;
        obj["id"] = id;
        obj["title"] = title;
        obj["content"] = content;
        obj["createdAt"] = nowStr;
        obj["updatedAt"] = nowStr;
        array.append(obj);
    }
    
    return saveJsonArray(array);
}

bool MemoStorage::deleteMemo(int id)
{
    QJsonArray array = loadJsonArray();
    QJsonArray newArray;
    
    bool found = false;
    for (int i = 0; i < array.size(); i++) {
        QJsonObject obj = array[i].toObject();
        if (obj["id"].toInt() != id) {
            newArray.append(obj);
        } else {
            found = true;
        }
    }
    
    if (!found) {
        return false;
    }
    
    return saveJsonArray(newArray);
}

int MemoStorage::getNextId()
{
    QJsonArray array = loadJsonArray();
    int maxId = 0;
    
    for (int i = 0; i < array.size(); i++) {
        QJsonObject obj = array[i].toObject();
        int id = obj["id"].toInt();
        if (id > maxId) {
            maxId = id;
        }
    }
    
    return maxId + 1;
}

